<template>
    <el-card style="max-width: 480px">
        <template #header>
            <div class="header-title">登录</div>
        </template>

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
                label-width="auto" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model.number="ruleForm.username" placeholder="请输入用户名"/>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password" autocomplete="off" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        登录
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
    </el-card>
</template>


<script setup>
import router from '@/router/router.js'
import { reactive, ref } from 'vue'
import {login} from '../api/userApi.js'
import messagePost from '@/utils/message.js'
import { useTokenStore } from '@/stores/tokenStore.js'

const ruleFormRef = ref()

const tokenStore = useTokenStore();
const ruleForm = reactive({
    username: '',
    password: ''
})

const rules = reactive({
  username: [
    { required: true, message: '用户名必填', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码必填', trigger: 'blur' },
  ],
});

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.value.resetFields()
}
const submitForm = (formEl) => {
    if (!ruleForm.username || !ruleForm.password) {
    messagePost({
        message: "请输入用户名和密码",
        type: 'error',
    });
    return;
    }
    
    formEl.validate(async (valid) => {
        if (valid) {
            console.log(ruleForm);
            let resp = await login(ruleForm)
            console.log(resp);
            if (resp){
                 // 存入token
                //  tokenStore.removeToken ();
                  tokenStore.updateToken(resp);
              // 回到首页
              router.push({path: '/index'})
            }
            else{
              //清空表单
              resetForm(ruleFormRef)
            }
        } else {
          resetForm(ruleFormRef)
        }
    })
}


</script>

<style scoped>

.header-title {
    text-align: center;
    font-weight: bold;
    text-transform: uppercase;
}
</style>